var wineApp = wineApp || {};
wineApp.order = (function() {
    var resourceURL = wineApp.tool.getResourceURL();
    var orderId = $.url().param()['orderId'];
    var addressId = $.url().param()['addrId'];
    var orderInfo = null;
    var initPage = function() {
        loadOrderInfo(orderId);
        initEvent();
        renderAddress();
    }
    var clearStorage = function() {
        var comeFrom = wineApp.tool.getKey("from");
        var selectedPlanKey = wineApp.tool.getKey("selectedPlan");
        var shopcarKey = wineApp.tool.getKey("shopcar");
        wineApp.localStorage.remove(comeFrom);
        wineApp.localStorage.remove(selectedPlanKey);
        if (comeFrom == 'shopcar') {
            wineApp.localStorage.remove(selectedPlanKey);
        }
    }
    var initEvent = function() {
        $(document).on('click', '.wine_order_btn', createOrder);
    }
    var loadOrderInfo = function(orderId) {
            if (orderId != null) {
                loadOrderInfoWithOrderId(orderId)
            } else {
                loadOrderInfoWithOutOrderId();
            }
        }
        //有order调用API
    var loadOrderInfoWithOrderId = function(orderId) {
            var ajaxUrl = wineApp.CONFIG.API.myorderdetail;
            wineApp.ajax.post(ajaxUrl, {
                orderid:orderId
            }).done(function(data) {

            })
        }
        //没有带orderId，就从localstorage取
    var loadOrderInfoWithOutOrderId = function() {
        var key = wineApp.tool.getKey("selectedPlan");
        var selectedPlans = wineApp.localStorage.get(key);
        var total = 0;
        $.each(selectedPlans, function(index, val) {
            total += renderPlan(val);
        });
        $("#amount").html(total);
    }

    var renderAddress = function() {
        loadAddr();
    }

    var createOrder = function() {
        if (_.isNull(orderInfo)) {
            wineApp.tool.toastError('请选择收货地址');
            return;
        }
        var key = wineApp.tool.getKey("selectedPlan");
        var selectedPlans = wineApp.localStorage.get(key);
        var prodList = _.map(selectedPlans, function(plan) {
            return _.pick(plan, ['count', 'prodid'])
        });
        var cartids = _.map(selectedPlans, function(plan) {
            return _.pick(plan, ['cartid'])
        });
        if (_.isNil(cartids)) {
            cartids = [];
        }
        // orderInfo = {
        //     sum: 3000,
        //     receiver: 'port',
        //     recphone: '13950003948',
        //     province: 'aa',
        //     city: 'city',
        //     town: 'town',
        //     address: 'address'
        // }
        wineApp.orderutil.createOrder(orderInfo, prodList, 'alipay', cartids);
        //clearStorage();
    }

    var loadAddr = function() {
        var ajaxUrl = wineApp.CONFIG.API.address;
        wineApp.ajax.post(ajaxUrl, {}).done(function(data) {
            var val = _.find(data.list, function(addr) {
                if (_.isNil(addressId)) {
                    return addr.defaultflag === 1;
                } else {
                    return addr.id == addressId
                }
            });
            if (data.list && data.list.length > 0 && _.isNil(val)) {
                val = data.list[0];
            }
            //todo
            var temp =
                '<dl>' +
                '<dt><a href=""><p><span>#phone#</span>#name#</p><em>#address#</em></a></dt>' +
                '</dl>';
            if (!_.isNil(val)) {
                $('#updateAddr').attr('href', 'address.html?referUrl=order.html');
            } else {
                $('#updateAddr').attr('href', 'newadd.html?referUrl=order.html');
            }
            if (!_.isNil(val)) {
                var address = "";
                if (val.province != null) address += val.province;
                if (val.city != null) address += val.city;
                if (val.town != null) address += val.town;
                if (val.address != null) address += val.address;
                var param = {};
                param.phone = val.phone;
                param.name = val.recname;
                param.address = address;
                param.addrId = val.id;
                for (var prop in param) {
                    var reg = new RegExp("#" + prop + "#", "gm");
                    temp = temp.replace(reg, param[prop]);
                }
                orderInfo = {
                    sum: 3000,
                    receiver: val.recname,
                    recphone: val.phone,
                    province: val.province,
                    city: val.city,
                    //town: 'town',
                    address: val.address
                }
                $('.wine_add').append(temp);
            }
        });
    }

    var renderPlan = function(selectedPlan) {
        console.log(selectedPlan)
        var template = '<dl>' +
            '<dt><a href="wine_detail.html?wineId=#id#"><img src="#wineImg#" /></a></dt>' +
            '<dd><a href="wine_detail.html?wineId=#id#">#wineName#<p><b>￥#price#</b>/<span>￥#oprice#</span></p><p class="wine_order_time">数量：#count#箱</p></a></dd>' +
            '</dl>';
        // var template = '<dl>' +
        //     '<dt><a href="wine_detail.html?wineId=#id#"><img src="#wineImg#" /></a></dt>' +
        //     '<dd>#wineName#' +
        //     '<p>￥#ammount#</p>' +
        //     '</dd>' +
        //     '</dl>';

        var param = {
            id: selectedPlan.prodid,
            //wineImg: resourceURL + "/" + selectedPlan.wineImg,
            wineImg: selectedPlan.wineImg,
            wineName: selectedPlan.wineName,
            ammount: selectedPlan.ammount,
            count: selectedPlan.count,
            price: selectedPlan.winePrice,
            oprice: selectedPlan.wineOverseasPrice
        }
        for (var prop in param) {
            var reg = new RegExp("#" + prop + "#", "gm");
            template = template.replace(reg, param[prop]);
        }
        $('.order_list').append(template);
        return selectedPlan.ammount;
    }

    return {
        initPage: initPage
    }
})();

$(document).ready(function() {
    $('.wine_footer').remove();
    wineApp.common.initHeaderIcon(0, true);
    wineApp.order.initPage();
});